package com.funever.fragment;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import net.tsz.afinal.annotation.view.ViewInject;
import com.activeandroid.ActiveAndroid;
import com.funever.combworkalerm.R;
import com.funever.entity.WorkType;
import com.funever.entity.Works;
import com.funever.utils.Utils;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class TenDaysTypeFragment extends BaseFragment {
	
	@ViewInject(id=R.id.ten_days)
	ListView ten_days_list;
	
	List<ShowWorks> showWorks = new LinkedList<ShowWorks>();
	
	List<WorkType> wtList;
	@ViewInject(id=R.id.submit,click="onClick")
	Button submit;
	@ViewInject(id=R.id.start_date)
	TextView startDate;
	@ViewInject(id=R.id.start_date_action,click="onClick")
	RelativeLayout startDateAction;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	MyAdapter myAdapter;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mainView = inflater.inflate(R.layout.ten_days_type, null);
		return mainView;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getActivity().setTitle("半月班表添加");
		Date start = null;
		try{
			String startStr = startDate.getText().toString();
			if(!startStr.equals("明天")){
				start = sdf.parse(startStr);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		getHalfMonthWork(start);
		wtList = WorkType.findAll();
		myAdapter = new MyAdapter();
		ten_days_list.setAdapter(myAdapter);
	}
	
	/**
	 * 获取冲设置时间开始后的半月的班表
	 * @param startDate
	 */
	public void getHalfMonthWork(Date startDate){
		showWorks.clear();
		//设置开始时间
		for(int i=0;i<15;i++){
			Calendar calendar = Calendar.getInstance();
			if(startDate!=null){
				calendar.setTime(startDate);
			}
			calendar.add(Calendar.DAY_OF_YEAR,i);
			ShowWorks sw = new ShowWorks();
			sw.setShowTitle(sdf.format(calendar.getTime())+" "+getDayForWeekCN(calendar));
			List<Works> l = Works.findAllByWhere("workDate = '"+sdf.format(calendar.getTime())+"'");
			Works sWorks;
			if(l!=null && l.size()>0){
				sWorks = l.get(0);
			}else{
				sWorks = new Works();
				sWorks.setDate(sdf.format(calendar.getTime()));
				sWorks.setWorkType("");
			}
			sw.setWorks(sWorks);
			showWorks.add(sw);
		}
	}
	
	public void onClick(View v){
		if(v == submit){
			try{
				ActiveAndroid.beginTransaction();  
				for(ShowWorks sw : showWorks){
					Works w = sw.getWorks();
					if(w.getWorkType().equals("")){
						continue;
					}
					w.save();
				}
				ActiveAndroid.setTransactionSuccessful();
				Toast.makeText(getActivity(), "保存完毕!", Toast.LENGTH_LONG).show();
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				ActiveAndroid.endTransaction();
			}
		}else if(v == startDateAction){
			showDatePick();
		}
	}
	
	public void showDatePick(){
		Calendar calendar = Calendar.getInstance();
		DatePickerDialog dpd = new DatePickerDialog(getActivity(), new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				Calendar select = Calendar.getInstance();
				select.set(Calendar.YEAR, year);
				select.set(Calendar.MONTH, monthOfYear);
				select.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				startDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(select.getTime()));
				getHalfMonthWork(select.getTime());
				myAdapter.notifyDataSetChanged();
			}
		}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
		dpd.show();
	}
	
	public String getDayForWeekCN(Calendar calendar){
		switch(calendar.get(Calendar.DAY_OF_WEEK)){
			case 1:
				return "星期天";
			case 2:
				return "星期一";
			case 3:
				return "星期二";
			case 4:
				return "星期三";
			case 5:
				return "星期四";
			case 6:
				return "星期五";
			case 7:
				return "星期六";
		}
		return "";
	}
	
	class ShowWorks{
		
		public String getShowTitle() {
			return showTitle;
		}

		public void setShowTitle(String showTitle) {
			this.showTitle = showTitle;
		}

		public Works getWorks() {
			return works;
		}

		public void setWorks(Works works) {
			this.works = works;
		}

		String showTitle;
		
		Works works;
	}
	
	class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return showWorks.size();
		}

		@Override
		public Object getItem(int position) {
			return showWorks.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHodler vh = null;
			if(convertView != null){
				vh = (ViewHodler) convertView.getTag();
			}else{
				convertView =  LayoutInflater.from(getActivity()).inflate(R.layout.work_list_item, null);
				vh = new ViewHodler();
				vh.title = (TextView) convertView.findViewById(R.id.date_title);
				vh.spinner =  (Spinner) convertView.findViewById(R.id.type_spinner);
				convertView.setTag(vh);
			}
			ShowWorks sw = showWorks.get(position);
			
			TextView title = vh.title;
			title.setText(sw.getShowTitle());
			
			Spinner types = vh.spinner;
			types.setAdapter(new MySpinnerAdapter());
			int index = 0;
			for(int i=0;i<wtList.size();i++){
				if(wtList.get(i).getName().equals(sw.getWorks().getWorkType())){
					index = i;
					break;
				}
			}
			types.setSelection(index);
			types.setOnItemSelectedListener(new MyOnItemSelectedListener(position));
			return convertView;
		}
		
		class ViewHodler{
			TextView title;
			Spinner spinner;
		}
	}
	
	class MyOnItemSelectedListener implements OnItemSelectedListener{
		
		int postion;
		
		public MyOnItemSelectedListener(int postion){
			this.postion = postion;
		}
		
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			showWorks.get(postion).getWorks().setWorkType(wtList.get(arg2).getName());
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	}
	
	class MySpinnerAdapter extends  BaseAdapter{

		@Override
		public int getCount() {
			return wtList.size();
		}

		@Override
		public Object getItem(int position) {
			return wtList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv = new TextView(getActivity());
			tv.setText(wtList.get(position).getName());
			tv.setTextSize(17);
			tv.setMinHeight(Utils.dip2px(getActivity(), 35));
			tv.setGravity(Gravity.CENTER_VERTICAL);
			return tv;
		}
		
	}
}
